<?php

namespace app\index\controller;

use think\Controller;
use extend\php_sdk\lib\CLogFileHandler;
use extend\php_sdk\lib\Log;
use php_sdk\lib\NativePay;
use php_sdk\lib\WxPayData\WxPayUnifiedOrder;
use php_sdk\lib\JsApiPay;
use php_sdk\lib\WxPayConfig;
use php_sdk\lib\WxPayData\WxPayOrderQuery;
use php_sdk\lib\WxPayData\WxPayMicroPay;
use php_sdk\lib\WxPayData\WxPayRefund;
class Wxpay extends Controller
{
    /**
     * 显示资源列表
     * @return \think\Response
     */
    public function index()
    {
        return view('index@wxpay/index');
    }

    /**
     * 扫码支付
     * @return bool|\php_sdk\lib\成功时返回，其他抛异常
     */
    public function getWxcode()
    {
//        //初始化日志
//        $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
//        $log = Log::Init($logHandler, 15);
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        $notify = new NativePay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $input->SetOut_trade_no("sdkphp123456789" . date("YmdHis"));
        $input->SetTotal_fee("1");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");

        $result = $notify->GetPayUrl($input);
//        halt($result);
//        $url2 = $result["code_url"];
        dump($result);die;
        return $result;
    }

    /**
     * JSAPI支付
     */
    public function jsApiPay()
    {
        //初始化日志
//        $logHandler = new CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
//        $log = Log::Init($logHandler, 15);

//①、获取用户openid
        try {
            $tools = new JsApiPay();
            $openId = $tools->GetOpenid();

            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody("test");
            $input->SetAttach("test");
            $input->SetOut_trade_no("sdkphp" . date("YmdHis"));
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new WxPayConfig();
            $order = WxPayApi::unifiedOrder($config, $input);
            echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            printf_info($order);
            $jsApiParameters = $tools->GetJsApiParameters($order);

            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();
        } catch (Exception $e) {
            Log::ERROR(json_encode($e));
        }
    }

    /**
     * 订单查询
     */
    public function orderquery()
    {
        //初始化日志
//$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
//$log = Log::Init($logHandler, 15);
        if ((isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""
                && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["transaction_id"], $matches))
            || (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""
                && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_trade_no"], $matches))) {
            header('HTTP/1.1 404 Not Found');
            exit();
        }

        if (isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != "") {
            try {
                $transaction_id = $_REQUEST["transaction_id"];
                $input = new WxPayOrderQuery();
                $input->SetTransaction_id($transaction_id);
                $config = new WxPayConfig();
                printf_info(WxPayApi::orderQuery($config, $input));
            } catch (Exception $e) {
                Log::ERROR(json_encode($e));
            }
            exit();
        }
        if (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != "") {
            try {
                $out_trade_no = $_REQUEST["out_trade_no"];
                $input = new WxPayOrderQuery();
                $input->SetOut_trade_no($out_trade_no);
                $config = new WxPayConfig();
                printf_info(WxPayApi::orderQuery($config, $input));
            } catch (Exception $e) {
                Log::ERROR(json_encode($e));
            }
            exit();
        }
    }

    /**
     * 订单退款
     */
    public function refund()
    {

        if ((isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""
                && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["transaction_id"], $matches))
            || (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""
                && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_trade_no"], $matches))
            || (isset($_REQUEST["total_fee"]) && $_REQUEST["total_fee"] != ""
                && !preg_match("/^[0-9]{0,10}$/i", $_REQUEST["total_fee"], $matches))
            || (isset($_REQUEST["refund_fee"]) && $_REQUEST["refund_fee"] != ""
                && !preg_match("/^[0-9]{0,10}$/i", $_REQUEST["refund_fee"], $matches))) {
            header('HTTP/1.1 404 Not Found');
            exit();
        }
//初始化日志
//        $logHandler = new CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
//        $log = Log::Init($logHandler, 15);

        function printf_info($data)
        {
            foreach ($data as $key => $value) {
                echo "<font color='#f00;'>$key</font> : " . htmlspecialchars($value, ENT_QUOTES) . " <br/>";
            }
        }

        if (isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != "") {
            try {
                $transaction_id = $_REQUEST["transaction_id"];
                $total_fee = $_REQUEST["total_fee"];
                $refund_fee = $_REQUEST["refund_fee"];
                $input = new WxPayRefund();
                $input->SetTransaction_id($transaction_id);
                $input->SetTotal_fee($total_fee);
                $input->SetRefund_fee($refund_fee);

                $config = new WxPayConfig();
                $input->SetOut_refund_no("sdkphp" . date("YmdHis"));
                $input->SetOp_user_id($config->GetMerchantId());
                printf_info(WxPayApi::refund($config, $input));
            } catch (Exception $e) {
                Log::ERROR(json_encode($e));
            }
            exit();
        }

//$_REQUEST["out_trade_no"]= "122531270220150304194108";
///$_REQUEST["total_fee"]= "1";
//$_REQUEST["refund_fee"] = "1";
        if (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != "") {
            try {
                $out_trade_no = $_REQUEST["out_trade_no"];
                $total_fee = $_REQUEST["total_fee"];
                $refund_fee = $_REQUEST["refund_fee"];
                $input = new WxPayRefund();
                $input->SetOut_trade_no($out_trade_no);
                $input->SetTotal_fee($total_fee);
                $input->SetRefund_fee($refund_fee);

                $config = new WxPayConfig();
                $input->SetOut_refund_no("sdkphp" . date("YmdHis"));
                $input->SetOp_user_id($config->GetMerchantId());
                printf_info(WxPayApi::refund($config, $input));
            } catch (Exception $e) {
                Log::ERROR(json_encode($e));
            }
            exit();
        }
    }

    /**
     * 订单退款查询
     */
    public function micropay()
    {
        /**
         * 注意：
         * 1、提交被扫之后，返回系统繁忙、用户输入密码等错误信息时需要循环查单以确定是否支付成功
         * 2、多次（一半10次）确认都未明确成功时需要调用撤单接口撤单，防止用户重复支付
         */
        if ((isset($_REQUEST["auth_code"]) && !preg_match("/^[0-9]{6,64}$/i", $_REQUEST["auth_code"], $matches))) {
            header('HTTP/1.1 404 Not Found');
            exit();
        }

//初始化日志
//        $logHandler = new CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
//        $log = Log::Init($logHandler, 15);



        if (isset($_REQUEST["auth_code"]) && $_REQUEST["auth_code"] != "") {
            try {
                $auth_code = $_REQUEST["auth_code"];
                $input = new WxPayMicroPay();
                $input->SetAuth_code($auth_code);
                $input->SetBody("刷卡测试样例-支付");
                $input->SetTotal_fee("1");
                $input->SetOut_trade_no("sdkphp" . date("YmdHis"));

                $microPay = new MicroPay();
                printf_info($microPay->pay($input));
            } catch (Exception $e) {
                Log::ERROR(json_encode($e));
            }
        }


    }


    //打印输出数组信息
    public function printf_info($data)
    {
        foreach ($data as $key => $value) {
            echo "<font color='#00ff55;'>$key</font> :  " . htmlspecialchars($value, ENT_QUOTES) . " <br/>";
        }
    }


}
